package com.pig4cloud.pigx.wms.webtools;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.pig4cloud.pigx.wms.dto.ERPOutStorageDTO;
import com.pig4cloud.pigx.wms.dto.ERPOutStorageItemDTO;
import com.pig4cloud.pigx.wms.dto.WCSResponseDTO;
import com.pig4cloud.pigx.wms.entity.SysToken;
import com.pig4cloud.pigx.wms.service.SysTokenService;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: 高欣
 * @Date: 2021/7/11 20:03
 * 签名方法
 */
@Service
@Slf4j
@RefreshScope
@RequiredArgsConstructor
public class TJWebToolsService {

	@Value("${tj.url}")
	private String url;

	@Value("${tj.appkey}")
	private String appkey;

	@Value("${tj.appSecret}")
	private String appSecret;

	@Value("${tj.refreshToken}")
	private String refreshToken;

	private String openToken;

	private final SysTokenService sysTokenService;

	public boolean updateToken() {

		String uri = url+"/auth/refreshToken?appKey="+appkey+"&grantType=refresh_token&refreshToken="+refreshToken;
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
		ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET,entity,String.class);

		String resJson = result.getBody();
		log.info("更新token接口返回的原始JSON:"+resJson);

		JSONObject jsonObject = JSONUtil.parseObj(resJson);

		String code = jsonObject.getStr("code");

		if("200".equals(code)){
			JSONObject resultJson = jsonObject.getJSONObject("result");
			String accessToken = resultJson.getStr("access_token");
			SysToken sysToken = sysTokenService.getById("tj_sys");
			log.info("T+系统更新之前的token是:"+sysToken.getSysToken());
			sysToken.setSysToken(accessToken);
			sysTokenService.updateById(sysToken);
			openToken = accessToken;
			log.info("T+系统更新之后的token是:"+accessToken);
			return true;
		}else{
			return false;
		}

	}

	public String getTokenFromDB() {
			SysToken sysToken = sysTokenService.getById("tj_sys");
			String accessToken = sysToken.getSysToken();
			openToken = accessToken;
			log.info("T+系统数据库保存的token是:"+accessToken);
			return accessToken;
	}

	public Map<String,ERPOutStorageDTO> getTJOuts(String startDateTime, String endDateTime){

		RestTemplate restTemplate = new RestTemplate();

		String requestQueryBody = "{\n"
				+ "    \"request\": {\n"
				+ "        \"ReportName\": \"ST_SaleDispatchDetailRpt\",\n"
				+ "        \"PageSize\": 100,\n"
				+ "        \"PageIndex\": 1,\n"
				+ "        \"ReportTableColNames\": \"VoucherDate,VoucherCode,BusinessTypeInfo,WarehouseCode,"
				+ "Warehouse,InventoryInfo,InventoryCode,Inventory,Specification,Unit,Quantity,Batch\",\n"
				+ "        \"SearchItems\": [\n"
				+ "            {\n"
				+ "                \"ColumnName\": \"VoucherDate\",\n"
				+ "                \"BeginDefault\": \""+startDateTime+"\",\n"
				+ "                \"BeginDefaultText\": \""+startDateTime+"\",\n"
				+ "                \"EndDefault\": \""+endDateTime+"\",\n"
				+ "                \"EndDeafultText\": \""+endDateTime+"\"\n"
				+ "            },\n"
				+ "            {\n"
				+ "                \"ColumnName\": \"VoucherCode\",\n"
				+ "                \"BeginDefault\": \"\",\n"
				+ "                \"BeginDefaultText\": \"\",\n"
				+ "                \"EndDefault\": \"\",\n"
				+ "                \"EndDeafultText\": \"\"\n"
				+ "            },\n"
				+ "            {\n"
				+ "                \"ColumnName\": \"Warehouse\",\n"
				+ "                \"BeginDefault\": \"\",\n"
				+ "                \"BeginDefaultText\": \"\",\n"
				+ "                \"EndDefault\": \"\",\n"
				+ "                \"EndDeafultText\": \"\"\n"
				+ "            }\n"
				+ "        ],\n"
				+ "        \"GroupItems\": [\n"
				+ "            {\n"
				+ "                \"IsGroup\": false,\n"
				+ "                \"IsSum\": false,\n"
				+ "                \"ColumnName\": \"VoucherCode\"\n"
				+ "            },\n"
				+ "            {\n"
				+ "                \"IsGroup\": false,\n"
				+ "                \"IsSum\": false,\n"
				+ "                \"ColumnName\": \"IDWarehouse\"\n"
				+ "            },\n"
				+ "            {\n"
				+ "                \"IsGroup\": false,\n"
				+ "                \"IsSum\": false,\n"
				+ "                \"ColumnName\": \"IDInventory\"\n"
				+ "            }\n"
				+ "        ]\n"
				+ "    }\n"
				+ "}";

		log.info("发送T+报表通用查询接口请求的body参数是:"+requestQueryBody);

		String openToken = this.getTokenFromDB();

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.add("openToken",openToken);
		headers.add("appKey",appkey);
		headers.add("appSecret",appSecret);
		HttpEntity<String> entity = new HttpEntity<>(requestQueryBody, headers);
		ResponseEntity<String> result = restTemplate.exchange(url+"/tplus/api/v2/reportQuery/GetReportData",
				HttpMethod.POST,entity,String.class);

		log.info("T+报表查询结果的JSON是:"+result.getBody());

		JSONObject jsonObject = JSONUtil.parseObj(result.getBody());

		if(0 == jsonObject.getInt("TotalRecords")){
			return null;
		}else{

			Map<String,ERPOutStorageDTO> erpOutStorageDTOMap = new HashMap<>();

			JSONObject jsonObjectDataSource = jsonObject.getJSONObject("DataSource");
			JSONArray jsonArrayRows = jsonObjectDataSource.getJSONArray("Rows");

			for(JSONObject jsonObjectOutItem : jsonArrayRows.toList(JSONObject.class)){

				if(!"0101".equals(jsonObjectOutItem.getStr("WarehouseCode"))){
					continue;
				}

				String outPageNo = jsonObjectOutItem.getStr("VoucherCode");

				if(erpOutStorageDTOMap.get(outPageNo) == null){

					ERPOutStorageDTO erpOutStorageDTO = new ERPOutStorageDTO();
					erpOutStorageDTOMap.put(jsonObjectOutItem.getStr("VoucherCode"),erpOutStorageDTO);
					erpOutStorageDTO.setOutPageNo(jsonObjectOutItem.getStr("VoucherCode"));
					erpOutStorageDTO.setStorageId(1);
					erpOutStorageDTO.setHuozId("1001");
					erpOutStorageDTO.setWlzxCode("6001");
					erpOutStorageDTO.setOutType("3");
					erpOutStorageDTO.setLocationNo("DSCK100001");

					List<ERPOutStorageItemDTO> erpOutStorageItemDTOS = new ArrayList<>();

					ERPOutStorageItemDTO erpOutStorageItemDTO = new ERPOutStorageItemDTO();
					erpOutStorageItemDTO.setSku(jsonObjectOutItem.getStr("InventoryCode"));
					erpOutStorageItemDTO.setAmount(jsonObjectOutItem.getInt("Quantity"));
					erpOutStorageItemDTO.setBatchNo(jsonObjectOutItem.getStr("Batch"));
					erpOutStorageItemDTO.setMinUnitName(jsonObjectOutItem.getStr("Unit"));

					erpOutStorageItemDTOS.add(erpOutStorageItemDTO);

					erpOutStorageDTO.setErpOutStorageItemDTOList(erpOutStorageItemDTOS);

				}else{

					ERPOutStorageDTO erpOutStorageDTO = erpOutStorageDTOMap.get(jsonObjectOutItem.getStr("VoucherCode"));
					List<ERPOutStorageItemDTO> erpOutStorageItemDTOS = erpOutStorageDTO.getErpOutStorageItemDTOList();

					ERPOutStorageItemDTO erpOutStorageItemDTO = new ERPOutStorageItemDTO();
					erpOutStorageItemDTO.setSku(jsonObjectOutItem.getStr("InventoryCode"));
					erpOutStorageItemDTO.setAmount(jsonObjectOutItem.getInt("Quantity"));
					erpOutStorageItemDTO.setBatchNo(jsonObjectOutItem.getStr("Batch"));
					erpOutStorageItemDTO.setMinUnitName(jsonObjectOutItem.getStr("Unit"));

					erpOutStorageItemDTOS.add(erpOutStorageItemDTO);

					erpOutStorageDTO.setErpOutStorageItemDTOList(erpOutStorageItemDTOS);

				}

			}
			//除去状态不合格的出库单
			for(String vCode : erpOutStorageDTOMap.keySet()){

				if(!checkApproveStatus(vCode)){
					erpOutStorageDTOMap.remove(vCode);
				}

			}

			return erpOutStorageDTOMap;
		}
	}

	private  boolean checkApproveStatus(String voucherCode){

		boolean isCaiwuSH = false;

		RestTemplate restTemplate = new RestTemplate();

		String requestQueryBody = "{\n"
				+ "  \"bizCode\": \"ST1021\",\n"
				+ "  \"voucherCode\": \""+voucherCode+"\"\n"
				+ "}";

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.add("openToken",openToken);
		headers.add("appKey",appkey);
		headers.add("appSecret",appSecret);
		HttpEntity<String> entity = new HttpEntity<>(requestQueryBody, headers);
		ResponseEntity<String> result = restTemplate.exchange(url+"/tplus/api/v2/WorkFlow/GetWFAuditInfosByCode",
				HttpMethod.POST,entity,String.class);

		log.info("出库单号:"+voucherCode+"T+审批情况查询结果的JSON是:"+result.getBody());

		JSONArray jsonArray = JSONUtil.parseArray(result.getBody());

		for(JSONObject jsonObject : jsonArray.toList(JSONObject.class)){

			if("财务审核".equals(jsonObject.getStr("Title")) && "批准".equals(jsonObject.getStr("Action"))){

				isCaiwuSH = true;
				break;
			}

		}

		return isCaiwuSH;
	}

}
